<template>
  <el-scrollbar>
    <h3>用户列表</h3>
    <div v-for="user in mesStore.userList" :key="user.id" :class="{'user-item':true,'active':acv == user.id}" @click="selectUser(user.id)">
      <div class="user-name">
        {{ user.name }}
      </div>
    </div>
  </el-scrollbar>

</template>

<script setup lang="ts">
import { ref, onMounted,onBeforeMount} from 'vue';
import messageStore from '@/stores/csr/MessageStore';
import userInf from '../../stores/user'


const props = defineProps<{}>();
const emit = defineEmits<{ (e: 'select-user', userId: string): void }>();

const userIf=userInf()

const mesStore=messageStore()

const socket=mesStore.webSocket

const acv = ref('')
function selectUser(userId:string) {
  acv.value = userId
  emit('select-user', userId);
}

onMounted(() => {

  const userList=mesStore.userList
  for(let i=0;i<userList.length;i++){
    const userExists=mesStore.messageRecord.find(user => user.id === userList[i].id)
    if(!userExists){
      mesStore.addMessageRecord(userList[i].id)
    }
    // mesStore.userList.push({
    //       id: userList[i].id,
    //       name: userList[i].name
    //     });
  }

  socket.on('message', (data: any) => {
      const {mark,senderId,userName,message} = data;
      const userExists=mesStore.userList.find(user => user.id === senderId)
      console.log(senderId+"_"+userExists)
      if (!userExists) {
        mesStore.userList.push({
          id: senderId,
          name: userName
        });
        // mesStore.addUser({id: senderId,name: userName})
        mesStore.addMessageRecord(senderId)
      }

      if(mark=="用户"){
        mesStore.toRecordMessage(senderId, { mark, senderId, userName, message })
      }

  });

  socket.connect(userIf.user.id);
});
</script>

<style lang="scss" scoped>
.user-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  cursor: pointer;
  background-color: #9ceb72;
  border-bottom: gray solid 2px;

  &:hover {
    background-color: #60d820;
  }



  .user-name {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 5px 0px;
  }
}

.active {
    background-color: #0aa707
  }

</style>
